<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ include file="/jsp/common/common.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<link href="<c:url value="/static/fullcalendar/fullcalendar.css"/>"
    rel='stylesheet' />
<link
    href="<c:url value="/static/fullcalendar/fullcalendar.print.css"/>"
    rel='stylesheet' media='print' />
<link rel="stylesheet" type="text/css"
    href="<c:url value="/static/jquery-easyui/themes/default/easyui.css"/>">
<link rel="stylesheet" type="text/css"
    href="<c:url value="/static/jquery-easyui/themes/icon.css"/>">
<link rel="Stylesheet" type="text/css"
    href="<c:url value="/static/css/jquery.ui.css"/>" />
<script type="text/javascript"
    src="<c:url value="/static/jquery-easyui/jquery-1.6.min.js"/>"></script>
<script type="text/javascript"
    src="<c:url value="/static/jquery-easyui/jquery.easyui.min.js"/>"></script>
<script type="text/javascript"
    src="<c:url value="/static/jquery-easyui/plugins/jquery.panel.js"/>"></script>
<script type="text/javascript"
    src="<c:url value="/static/jquery-easyui/plugins/jquery.datagrid.js"/>"></script>
<script type="text/javascript"
    src="<c:url value="/static/jquery-easyui/plugins/jquery.messager.js"/>"></script>
<script type="text/javascript"
    src="<c:url value="/static/jquery-easyui/ext-for-framework.js.jsp"/>"></script>
<script type="text/javascript"
    src="<c:url value="/static/jquery-easyui/locale/easyui-lang-zh_CN.js"/>"></script>
<script type="text/javascript"
    src="<c:url value="/static/js/common.js"/>"></script>
<script type="text/javascript"
    src="<c:url value="/static/js/Loading.js"/>"></script>
<script type="text/javascript"
    src="<c:url value="/static/js/showMsg.js"/>"></script>
<script type="text/javascript"
    src="<c:url value="/static/listBox/jquery.clever.listbox.js"/>"></script>
<script>
    function initList(listDisplayEId) {
        $('#' + listDisplayEId)
                .datagrid(
                        {
                            url : "<c:url value="/distributor/findMaterForDistributor.do"/>",
                            nowrap : false,
                            striped : true,
                            collapsible : true,
                            remoteSort : true,
                            notSelectByRow : false,
                            onLoadError : function() {
                                $.messager.alert('错误', '获取数据失败，请与管理员联系！',
                                        'error');
                            },
                            onLoadSuccess : function() {
                                $(".datagrid-row").mouseover(
                                        function(e) {
                                            if (checkHover(e, this)) {
                                                var foodId = $(this).find('td')
                                                        .eq(2).text();
                                                var index = $('#listDisplay')
                                                        .datagrid(
                                                                'getRowIndex',
                                                                foodId);
                                                $('#listDisplay').datagrid('beginEdit', index);
                                            }
                                        });

                            }

                        });

    };

    function initList2(listDisplayEId) {
        $('#' + listDisplayEId)
                .datagrid(
                        {
                            nowrap : false,
                            striped : true,
                            collapsible : true,
                            remoteSort : true,
                            notSelectByRow : false,
                            toolbar : [ {
                                id : listDisplayEId + '_btn_edit',
                                text : '提交',
                                iconCls : 'icon-edit',
                                handler : function() {
                                    //判断供货商是否存在
                                    
                                	
                                    var rows = $('#listDisplay2').datagrid('getRows');
                                    for (var i = 0; i < rows.length; i++) {
                                        var rowIndex = $('#listDisplay2').datagrid('getRowIndex',rows[i]['orderId']);
                                        $('#listDisplay2').datagrid('endEdit',rowIndex);
                                    }
                                    var row = $('#listDisplay2').datagrid('getRows');
                                    if (row.length == 0) {
                                        $.messager.alert('提示', '购物车中没有商品！','info');
                                        return;
                                    } else {
                                        var userList = new Array();
                                        var jsonFater;
                                        for (var i = 0; i < row.length; i++) {
                                            if (!isNumber(row[i]['materWeight'])) {
                                                $.messager.alert("提示","'"+ row[i]['materName'] + "'数量请填写数字！",'info');
                                                beginEditList(row,'#listDisplay2','orderId');
                                                return;
                                            }
                                            
                                            var jsonSun = "{ordMaterId:'"
                                                    + row[i]['materId']
                                                    + "',orderDate:'"
                                                    + "${OrderDistributorPo.ordDate }"
                                                    + "',materLevel:'"
                                                    + row[i]['materLevel']
                                                    + "',materWeight:'"
                                                    + row[i]['materWeight']
                                                    + "',code:'"
                                                    + row[i]['code']
                                                    + "'}";
                                            userList.push(jsonSun);
                                        }
                                        jsonFater = JSON.stringify(userList);
                                        var str = "json=" + jsonFater;
                                        document.getElementsByName("materdategridList")[0].value = jsonFater;
                                        $.messager.confirm('提示', '是否提交记录？',
                                                function(r) {
                                                    //方法函数 进入后台
                                                    if (r) {
                                                        addMater();
                                                    }
                                                });
                                    }
                                }
                            },
                            {
                                id : listDisplayEId + '_btn_remove',
                                text : '删除',
                                iconCls : 'icon-remove',
                                handler : function() {
                                	deleteRow();
                                }
                                
                            }],
                        });
    };
    function beginEditList(rows, list, id) {
        for (var i = 0; i < rows.length; i++) {
            var rowIndex = $(list).datagrid('getRowIndex', rows[i][id]);
            $(list).datagrid('beginEdit', rowIndex);
        }
    }
    //删除选择行
    function deleteRow(){
        var rows = $('#listDisplay2').datagrid('getSelections');
        if(rows.length == 0){
            $.messager.alert('提示','请选择一条记录操作！','info');
            return;
        } else {
            var length = rows.length -1;
            for (var i = length; i > -1; i--) {
                var rowIndex = $('#listDisplay2').datagrid('getRowIndex',
                        rows[i]['orderId']);
                $('#listDisplay2').datagrid('deleteRow', rowIndex);
            }
        }
    }
    $(document).ready(function() {
        init();
        initList2('listDisplay2');
        initList('listDisplay');
    });

    function init() {
    	$('#materType').combobox({
            url : "<c:url value='/mater/pulldownMaterType.do?space=1'/>",
            editable : true, //不可编辑状态  
            cache : false,
            panelHeight : '150',
            valueField : 'materType',
            textField : 'materTypename',
        });
    }
    function addMater() {
        $('#AddMaterForm').form('submit', {
            url : '<c:url value='/distributor/commitMaterOrderForDistributorForUpdate.do'/>', //查询提交路径
            onSubmit : function()//提交按钮相应函数
            {
                return $('#AddMaterForm').form('validate');
            },
            success : function(data) {
                data = eval("(" + data + ")");
                if (data.success) {
                    $.messager.alert("提示", "提交成功！", 'info');
                    var rows = $('#listDisplay2').datagrid('getRows');
                    if(rows.length == 0){
                        return;
                    } else {
                        var length = rows.length -1;
                        for (var i = length; i > -1; i--) {
                            var rowIndex = $('#listDisplay2').datagrid('getRowIndex',rows[i]['orderId']);
                            $('#listDisplay2').datagrid('deleteRow', rowIndex);
                        }
                    }
                } else {
                    var message = "";
                    if (data.msg == "ms001") {
                        message = "订单中已有购物车中的材料，请直接改实际送货数量。";
                    } else if (data.msg == "msg001") {
                        message = "选择材料的时间已过，请联系采购部。";
                    } else if (data.msg == "msg002") {
                        message = "当日已有订单请在当日订单里临时添加材料！";
                    }
                    $.messager.alert("提示", message, 'warning');
                }
            },
            error : function() {
                $.messager.alert("错误", "系统错误，请联系管理员！", 'error');
                return;
            }
        });

    }

    function searchInfo() {
        var midvale;
        if ($('#materId').val() == '') {
            midvale = 0;
        } else {
            midvale = $('#materId').val();
        }

        if ($('#materType').combobox('getValue') == '') {
            $('#listDisplay').datagrid('load', {
                materType : 0,
                materName : $('#materName').val(),
                materId : midvale
            });
        } else {
            $('#listDisplay').datagrid('load', {
                materType : $('#materType').combobox('getValue'),
                materName : $('#materName').val(),
                mid : midvale
            });
        }
    }
    
    document.onkeydown = keyDownSearch;
    function keyDownSearch(e) {
        // 兼容FF和IE和Opera    
        var theEvent = e || window.event;
        var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
        if (code == 13) {
            searchInfo();//具体处理函数    
            return false;
        }
        return true;
    }

    var dataLeft;
    function initDateLeft() {
        $.ajax({
            async : false,
            url : "<c:url value='/supplier/getAllSup.do'/>",
            type : "post",
            success : function(data) {
                dataLeft = data;
                if (typeof (dataLeft) == 'string' && dataLeft != '') {
                    dataLeft = JSON.parse(dataLeft);
                }
            }
        });
    }
    //加入报货清单按钮
    function formatJiantou(val, rowData, rowIndex) {
        return "<a href='###' onclick='shoppingStore("
                + rowIndex
                + ")'><img height='30' width='80' src='../images/jiantou.jpg'/></a>";
    }
    //加入报货清单
    function shoppingStore(rowIndex) {
        var rowData;
        var a;
        var dateone;
        $('#listDisplay').datagrid('endEdit', rowIndex);
        var rowDateAll = $('#listDisplay').datagrid('getRows');
        var rowDateAll2 = $('#listDisplay2').datagrid('getRows');
        var id = 0;//纪录最大id id 用语标记报货表的数据

        //取得最大orderId 序号
        if (rowDateAll2.length > 0) {
            id = rowDateAll2[rowDateAll2.length - 1]['orderId'] + 1;
        } else {
            id = 1;
        }
        for (var i = 0; i < rowDateAll.length; i++) {
            if (rowIndex == $('#listDisplay').datagrid('getRowIndex',
                    rowDateAll[i]['materId'])) {
                $('#listDisplay').datagrid('endEdit', rowIndex);
                rowData = rowDateAll[i];
                var materIdDate = rowData['materId'];
                var str = "materId=" + rowData['materId'] + "&date="
                        + "${OrderDistributorPo.ordDate }";
                var _materWeight = rowData['materWeight'];
                var _materlevel = rowData['materLevel'];

                $.ajax({
                            type : 'post',
                            async : false,
                            url : "<c:url value='/supplierPurchases/getMaterForPurchases.do'/>"
                                    + "?" + str,
                            dataType : "json",// 设置查询参数及提交路径
                            success : function(data) {
                                if (typeof (data) == 'string') {
                                    data = JSON.parse(data);
                                }
                                if (data.success) {
                                    $('#listDisplay2').datagrid('appendRow',
                                                    {
                                                        orderId : id,
                                                        materId : data.materVo.materId,
                                                        materName : data.materVo.materName,
                                                        materWeightNeed : data.materVo.materWeightNeed,
                                                        materWeight : _materWeight,
                                                        materNumberStore : data.materVo.materStoreNumber,
                                                        unit : data.materVo.unit,
                                                        materType : data.materVo.materType,
                                                        brands : data.materVo.brands,
                                                        specifications : data.materVo.specifications,
                                                        materLevel :_materlevel
                                                    });
                                    
                                    $('#listDisplay2').datagrid('beginEdit', $('#listDisplay2').datagrid('getRowIndex',id));

                                }
                            },
                            error : function() {
                                $.messager.alert("错误", "系统错误，请联系管理员！", 'error');
                            }
                        });
                break;
            }
        }

    }
</script>
</head>
<body>
        <table width="98%">
            <tr>
                <td>
                    <div
                        style="height: auto; width: 100%; background: #fafafa; padding: 2px;"
                        class="easyui-panel" title="&nbsp&nbsp&nbsp&nbsp&nbsp订单信息"
                        collapsible="true" minimizable="false" maximizable="false"
                        closable="false">
                        <form id="AddMaterForm" name="AddMaterForm" method="post"
                            enctype="multipart/form-data">
                        <table cellpadding="5">
                            <tr>
                                <td>订单号</td>
                                <td><input class="easyui-validatebox" name="ordId"
                                    id="ordId" editable="false" readOnly='true' value="${OrderDistributorPo.ordId }" /></td>
                            </tr>
                            <tr>
                                <td><input class="easyui-validatebox" type="hidden"
                                    name="materdategridList" /></td>
                                <td><input class="easyui-validatebox" type="hidden" value="${OrderDistributorPo.ordSupId }"
                                    name="ordSupId" id="ordSupId" editable="false" /></td>
                                <td><input class="easyui-validatebox" type="hidden" value="${OrderDistributorPo.ordDate }"
                                    name="orderDate" id="orderDate" editable="false" /></td>
                            </tr>
                        </table>
                        </form>
                        
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div
                        style="height: auto; width: 100%; background: #fafafa; padding: 5px;"
                        class="easyui-panel" title="查询" iconCls="icon-search"
                        collapsible="true" minimizable="false" maximizable="false"
                        closable="false">
                        <form id="searchForm" name="searchForm" method="post"
                            action="userlist.txt"
                            onsubmit="return searchDGData(this.id,'listDisplay');">
                            <div>
                                <table cellpadding="5">
                                    <tr>
                                        <td colspan="3"><span style="color: red;">(注意!材料名支持拼音和首字母检索)</span></td>
                                    </tr>
                                    <tr>
                                        <td>材料ID：</td>
                                        <td><input class="easyui-numberbox" id="materId"
                                            editable="true" name="materId" validType="length[1,30]"></input></td>
                                        <td>材料名：</td>
                                        <td><input class="easyui-validatebox" id="materName"
                                            editable="true" name="materName"></input></td>

                                        <td>类别：</td>
                                        <td><input class="easyui-combobox" id="materType"
                                            editable="false" name="materType"></input></td>
                                        <!-- <td>供货商名：</td> -->
                                        <td><input type="button" onclick="searchInfo()"
                                            value="查询"></td>
                                    </tr>
                                </table>
                            </div>
                        </form>
                    </div>
                </td>
            </tr>
        </table>
        <table width="98%">
            <tr style="height: 12px;"></tr>
            <tr>
                <td>
                    <table id="listDisplay" title="选取材料列表" iconCls="icon-list"
                        singleSelect="false" idField="materId" loadMsg="请稍候......"
                        pagination="true" pageSize="10" pageList="[10,20,30,40,50,100]"
                        sortName="mid" rownumbers="true" sortOrder="asc">
                        <thead>
                            <tr>
                                <th field="materRole" width="25" align="center" checkbox="true"
                                    hidden='true'></th>
                                <th field="mid" width="80" sortable="true" hidden="true">ID</th>
                                <th field="materId" width="40" sortable="true">材料ID</th>
                                <th field="materName" width="80" sortable="true">材料名</th>
                                <th field="materLevel" width="80" sortable="true" >等级</th>
                                <th field="brands" width="70" sortable="true">品牌</th>
                                <th field="specifications" width="70" sortable="true">规格</th>
                                <th field="materType" width="60" sortable="true"
                                    formatter="formatFoodType1">种类</th>
                                <th field="materWeightNeed" width="70" sortable="true">需求数量</th>
                                <th field="materStoreNumber" width="70" sortable="true">库存数量</th>
                                <th field="materWeight" width="70" sortable="true" editor="text">要货数量</th>
                                <th field="unit" width="40" sortable="true">单位</th>
                                <th field="button" width="120" align="center"
                                    formatter="formatJiantou">加入采购清单</th>
                            </tr>
                        </thead>
                    </table>
                </td>
            </tr>
            <tr style="height: 12px;"></tr>
            <tr>
                <td>
                    <table id="listDisplay2" title="我的采购清单" width="100%"
                        iconCls="icon-list" singleSelect="true" idField="orderId"
                        loadMsg="请稍候......" pagination="false" sortName="sid"
                        rownumbers="true" sortOrder="asc">
                        <thead>
                            <tr>
                                <th field="id" width="25" align="center" checkbox="true"></th>
                                <th field="orderId" width="25" align="center"></th>
                                <th field="materId" width="60" sortable="true">材料ID</th>
                                <th field="materName" width="80" sortable="true">材料名</th>
                                <th field="materLevel" width="80" sortable="true" >等级</th>
                                <th field="brands" width="70" sortable="true">品牌</th>
                                <th field="specifications" width="70" sortable="true">规格</th>
                                <th field="materType" width="60" sortable="true"
                                    formatter="formatFoodType1">种类</th>
                                <th field="materWeightNeed" width="70" sortable="true">需求数量</th>
                                <th field="materNumberStore" width="70" sortable="true">库存数量</th>
                                <th field="materWeight" width="70" sortable="true" editor="text">要货数量</th>
                                <th field="unit" width="40" sortable="true">单位</th>
                                <th field="code" width="60" sortable="true" editor="text">摊位号</th>
                            </tr>
                        </thead>
                    </table>
                </td>
            </tr>
        </table>
</body>
</html>
